package com.qipay.admin.sp.controller;

import com.qipay.admin.BaseController;
import com.qipay.admin.login.AuthPassport;
import com.qipay.admin.sp.vo.SpChannelDTO;
import com.qipay.admin.sp.vo.SpChannelPostDTO;
import com.qipay.admin.sp.vo.SpDTO;
import com.qipay.admin.sp.vo.SpUserDTO;
import com.qipay.admin.tags.PageModel;
import com.qipay.admin.utils.SiteHelper;
import com.qipay.baas.model.*;
import com.qipay.core.entity.Result;
import com.qipay.core.entity.ValueObject;
import com.qipay.core.help.BeanHelper;
import com.qipay.core.help.ResultHelper;
import com.qipay.cp.CpService;
import com.qipay.scalar.type.ChannelTypeEnum;
import com.qipay.security.UserDetailsServiceImpl;
import com.qipay.sp.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/sp")
public class SpController extends BaseController {

    @Autowired
    SpService spService;
    @Autowired
    SpChannelService spChannelService;
    @Autowired
    SpApiConfigService spApiConfigService;
    @Autowired
    SpConfigService spConfigService;
    @Autowired
    CpService cpService;
    @Autowired
    CpSpChannelService cpSpChannelService;
    @Autowired
    SpUserService spUserService;

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/zhidingCp/save"}, method = RequestMethod.POST)
    public ModelAndView saveZhidingCp(
            @RequestParam(name = "agentId", required = false, defaultValue = "0") int agentId,
            @RequestParam(name = "cpIds", required = false, defaultValue = "") List<Integer> cpIds,
            @RequestParam(name = "spChannelId", required = false, defaultValue = "0") int spChannelId
    ) {
        SpChannel spChannel = spChannelService.getOneById(spChannelId);
        cpSpChannelService.delete(spChannelId, agentId);
        if (spChannel != null && cpIds != null && cpIds.size() > 0) {
            for (int i = 0; i < cpIds.size(); i++) {
                CpSpChannel cpSpChannel = new CpSpChannel();
                cpSpChannel.setCpId(cpIds.get(i));
                cpSpChannel.setChannelType(spChannel.getChannelType().intValue());
                cpSpChannel.setSpId(spChannel.getSpId().intValue());
                cpSpChannel.setSpChannelId(spChannelId);
                cpSpChannelService.insert(cpSpChannel);
            }
        }

        return zhidingCp(agentId, spChannelId);
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/zhidingCp"}, method = RequestMethod.GET)
    public ModelAndView zhidingCp(
            @RequestParam(name = "agentId", required = false, defaultValue = "0") int agentId,
            @RequestParam(name = "spChannelId", required = false, defaultValue = "0") int spChannelId
    ) {
        SpChannel spChannel = spChannelService.getOneById(spChannelId);
        List<CpSpChannel> cpSpChannels = cpSpChannelService.selectBySpChannelId(spChannel.getId());
        List<Integer> cpIds = new ArrayList<>();
        if (cpSpChannels != null && cpSpChannels.size() > 0) {
            for (CpSpChannel csc : cpSpChannels) {
                cpIds.add(csc.getCpId());
            }
        }

        ModelAndView view = createModelAndView("zhiding-cp");
        List<CpZhiding> cpZhidings = cpService.findAllZd(agentId);
        List<Cp> agents = cpService.findByType((byte) 2, 1, 10000);
        view.addObject("cpZhidings", cpZhidings);
        view.addObject("agentId", agentId);
        view.addObject("spChannelId", spChannelId);
        view.addObject("agents", agents);
        view.addObject("cpIds", cpIds);

        return view;
    }


    @AuthPassport(key = "admin")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView list(@RequestParam(value = "name", required = false, defaultValue = "") String name,
                             @RequestParam(value = "service", required = false, defaultValue = "") String service,
                             @RequestParam(value = "bank", required = false, defaultValue = "") String bank,
                             @RequestParam(value = "s", required = false, defaultValue = "") Byte state,
                             @RequestParam(value = "spUserName", required = false, defaultValue = "") String spUserName,
                             @RequestParam(value = "p", required = false, defaultValue = "0") int p,
                             @RequestParam(value = "pz", required = false, defaultValue = "50") int pz) throws UnsupportedEncodingException {
        ModelAndView view = createModelAndView("sp-list");
        //查总条数
        long total = spService.countByCondition(name, service, bank, state, spUserName);
        List<Sp> lst = null;
        //查列表
        if (total > 0) {
            lst = spService.getByCondition(name, service, bank, state, p, pz, spUserName);
        }

        view.addObject("total", total);
        view.addObject("lst", lst);

        PageModel pageModel = new PageModel();
        pageModel.setPage(p);
        pageModel.setPageSize(pz);

        if (name != null) name = URLEncoder.encode(name, "utf8");
        if (service != null) service = URLEncoder.encode(service, "utf8");
        if (bank != null) bank = URLEncoder.encode(bank, "utf8");

        pageModel.setUrl(String.format("?name=%s&service=%s&bank=%s&s=%s", name, service, bank, SiteHelper.getEmptyStr(state, "")));
        pageModel.setTotal(total);
        view.addObject("page", pageModel);

        view.addObject("isadd", "1");
        //取出供号商字典
        List<ValueObject> query = spUserService.query();
        List<SpUserDTO> spUserDTOS = BeanHelper.valueObjectToBean(query, SpUserDTO.class);
        view.addObject("spUsers", spUserDTOS);
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/{id:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView detail(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                               @PathVariable @NotNull int id) {
        ModelAndView view = createModelAndView("sp-detail");
        if (id > 0) {
            Sp sp = spService.get(id);
            if (sp != null && sp.getId() != null) {
                view.addObject("isadd", "0");
                view.addObject("detail", sp);

                //取出供号商字典
                List<ValueObject> query = spUserService.query();
                List<SpUserDTO> spUserDTOS = BeanHelper.valueObjectToBean(query, SpUserDTO.class);
                view.addObject("spUsers", spUserDTOS);
                return view;
            }
        }
        return new ModelAndView("redirect:/sp");
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/add"}, method = RequestMethod.GET)
    public ModelAndView add() {
        ModelAndView view = createModelAndView("sp-detail");
        view.addObject("isadd", "1");
        //取出供号商字典
        List<ValueObject> query = spUserService.query();
        List<SpUserDTO> spUserDTOS = BeanHelper.valueObjectToBean(query, SpUserDTO.class);
        view.addObject("spUsers", spUserDTOS);
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(SpDTO dto) {

        if (dto != null) {
            Sp sp = null;
            if (dto.getId() != null && dto.getId() > 0) {
                sp = spService.get(dto.getId().intValue());
                BeanUtils.copyProperties(dto, sp);
                sp.setUpdateDate(new Date());
                spService.update(sp);
            } else {
                sp = new Sp();
                BeanUtils.copyProperties(dto, sp);
                sp.setCreateDate(new Date());
                sp.setUpdateDate(new Date());
                sp.setDeleteFlag((byte) 0);
                spService.insert(sp);
            }
        }
        return "redirect:/sp";
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = "/saveZfbNo", method = RequestMethod.POST)
    @ResponseBody
    public Result saveZfbNo(SpDTO dto) {
        Sp sp = null;
        if (dto != null && dto.getId() != null && dto.getId() > 0) {
            sp = spService.get(dto.getId().intValue());
            sp.setZfbNo(dto.getZfbNo());
            sp.setUpdateDate(new Date());
            spService.update(sp);
            return ResultHelper.success("修改支付豁亮 账号号成功");
        }
        return ResultHelper.error("修改支付宝账号失败");
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/{id:[\\d]+}/channel"}, method = RequestMethod.GET)
    public ModelAndView channel(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                @PathVariable @NotNull int id) {
        Sp sp = spService.get(id);
        if (sp != null && sp.getId() != null) {
            ModelAndView view = createChannelDTOList(spChannelService.selectBySpId(id), sp);
            view.addObject("detail", sp);
            return view;
        }
        return new ModelAndView("redirect:/sp");
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/channel"}, method = RequestMethod.GET)
    public ModelAndView channelAll(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser) {
        return createChannelDTOList(spChannelService.all(), null);
    }

    ModelAndView createChannelDTOList(List<SpChannel> spChannels, Sp sp) {
        ModelAndView view = createModelAndView("sp-channel-list");
        if (spChannels != null && spChannels.size() > 0) {
            List<SpChannelDTO> dtoList = new ArrayList<>(spChannels.size());
            for (SpChannel spChannel : spChannels) {
                spChannel.setFeeRecharge(spChannel.getFeeRecharge().multiply(SiteHelper.decimalFor100));
                SpChannelDTO dto = new SpChannelDTO();
                BeanUtils.copyProperties(spChannel, dto);
                if (sp != null) {
                    dto.setSp(sp);
                } else {
                    dto.setSp(spService.get(dto.getSpId().intValue()));
                }

                dtoList.add(dto);
            }
            view.addObject("lst", dtoList);
        }
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/channel/{id:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView channelDetail(@PathVariable @NotNull int id) {
        ModelAndView view = createModelAndView("sp-channel-detail");
        SpChannel spChannel = spChannelService.get(id);
        spChannel.setFeeRecharge(spChannel.getFeeRecharge().multiply(SiteHelper.decimalFor100));
        view.addObject("detail", spChannel);
        view.addObject("isadd", "0");
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/channel/add"}, method = RequestMethod.GET)
    public ModelAndView channelDetailAdd(@RequestParam(value = "spid", required = true, defaultValue = "0") int id) {
        ModelAndView view = createModelAndView("sp-channel-detail");
        view.addObject("isadd", "1");
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/channel/save"}, method = RequestMethod.POST)
    public String saveChannel(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                              SpChannelPostDTO dto) {
        SpChannel spChannel = spChannelService.getOneBySpIdAndChannelType(dto.getSpId(), ChannelTypeEnum.getByType(dto.getChannelType()));
        if (dto.getId() != null) {
            //update.  if itself no check .
            if (dto.getId() != spChannel.getId()) {
                //update other
                if (dto.getChannelType() == spChannel.getChannelType() && dto.getSpId() == spChannel.getSpId()) {
                    return String.format("redirect:/sp/channel/%s?error=1", dto.getId().toString());
                }
            }
        } else {
            //insert

            if (spChannel != null && dto.getChannelType() == spChannel.getChannelType() && dto.getSpId() == spChannel.getSpId()) {
                return String.format("redirect:/sp/channel/%s?spid=%s&error=1", "add", dto.getSpId().intValue());
            }
        }
        if (dto.getId() != null && dto.getId().intValue() > 0) {
            //update
            dto.setFeeRecharge(dto.getFeeRecharge().divide(SiteHelper.decimalFor100));
            SpChannel db = spChannelService.get(dto.getId());
            if (db != null && db.getId() > 0) {
                BeanUtils.copyProperties(dto, db);
                db.setUpdateDate(new Date());
                spChannelService.update(db);
            }

        } else {
            dto.setFeeRecharge(dto.getFeeRecharge().divide(SiteHelper.decimalFor100));
            SpChannel db = new SpChannel();
            BeanUtils.copyProperties(dto, db);
            db.setUpdateDate(new Date());
            db.setCreateDate(new Date());
            spChannelService.insert(db);

        }
        return String.format("redirect:/sp/%s/channel", dto.getSpId().toString());
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/{id:[\\d]+}/api"}, method = RequestMethod.GET)
    public ModelAndView apiList(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                @PathVariable @NotNull int id) {
        Sp sp = spService.get(id);
        if (sp != null && sp.getId() != null) {
            ModelAndView view = createModelAndView("sp-api-list");
            view.addObject("detail", sp);
            view.addObject("lst", spApiConfigService.selectBySpId(id));
            return view;
        }
        return new ModelAndView("redirect:/sp");
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/api/{id:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView apiDetail(@PathVariable @NotNull int id) {
        ModelAndView view = createModelAndView("sp-api-detail");
        SpApiConfig spApiConfig = spApiConfigService.get(id);
        view.addObject("detail", spApiConfig);
        // view.addObject("api", spApiConfigService.selectAllApiType());
        view.addObject("isadd", "0");
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/api/add"}, method = RequestMethod.GET)
    public ModelAndView apiDetailAdd(@RequestParam(value = "spid", required = true, defaultValue = "0") int id) {
        ModelAndView view = createModelAndView("sp-api-detail");
        view.addObject("isadd", "1");
        // view.addObject("api", spApiConfigService.selectAllApiType());
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/api/save"}, method = RequestMethod.POST)
    public String saveApi(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                          SpApiConfig dto) {
        if (dto.getId() != null && dto.getId().intValue() > 0) {
            //update
            SpApiConfig db = spApiConfigService.get(dto.getId().intValue());
            if (db != null && db.getId() > 0) {
                BeanUtils.copyProperties(dto, db);
                spApiConfigService.update(db);
            }
        } else {
            SpApiConfig db = new SpApiConfig();
            BeanUtils.copyProperties(dto, db);
            spApiConfigService.insert(db);
        }
        return String.format("redirect:/sp/%s/api", dto.getSpId().toString());
    }


    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/{id:[\\d]+}/config"}, method = RequestMethod.GET)
    public ModelAndView apiConfigList(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                      @PathVariable @NotNull int id) {
        Sp sp = spService.get(id);
        if (sp != null && sp.getId() != null) {
            ModelAndView view = createModelAndView("sp-config-list");
            view.addObject("detail", sp);
            view.addObject("lst", spConfigService.getBySpId((long) id));
            return view;
        }
        return new ModelAndView("redirect:/sp");
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/config/{id:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView apiConfigDetail(@PathVariable @NotNull int id) {
        ModelAndView view = createModelAndView("sp-config-detail");
        SpConfig spConfig = spConfigService.get(id);
        view.addObject("detail", spConfig);
        view.addObject("isadd", "0");
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/config/add"}, method = RequestMethod.GET)
    public ModelAndView apiConfigDetailAdd(@RequestParam(value = "spid", required = true, defaultValue = "0") int id) {
        ModelAndView view = createModelAndView("sp-config-detail");
        view.addObject("isadd", "1");
        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/config/save"}, method = RequestMethod.POST)
    public String saveConfig(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                             SpConfig dto) {
        if (dto.getId() != null && dto.getId().intValue() > 0) {
            //update
            SpConfig db = spConfigService.get(dto.getId().intValue());
            if (db != null && db.getId() > 0) {
                BeanUtils.copyProperties(dto, db);
                spConfigService.update(db);
            }
        } else {
            SpConfig db = new SpConfig();
            BeanUtils.copyProperties(dto, db);
            spConfigService.insert(db);
        }
        return String.format("redirect:/sp/%s/config", dto.getSpId().toString());
    }
}
